package com.dabai.sas.activitys

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.dabai.sas.R
import com.dabai.sas.utils.DabaiUtils
import com.dabai.sas.utils.FileUtil
import com.dabai.sas.utils.UriUtils
import com.google.android.material.chip.Chip
import com.tbruyelle.rxpermissions3.RxPermissions
import java.io.File
import java.util.*


class TextViewerActivity : AppCompatActivity() {

    val TAG = "DABAI"

    lateinit var tv1: TextView
    lateinit var tv2: TextView
    lateinit var chip1: Chip


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_text_viewer)

        Objects.requireNonNull(supportActionBar)!!.setDisplayHomeAsUpEnabled(true)

        val rxPermissions = RxPermissions(this)
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            DabaiUtils.showToast(applicationContext, "请点击申请'储存权限'!")
            startActivity(Intent(this, PermissionsActivity::class.java))
            finish()
            return
        }

        tv1 = findViewById(R.id.textView1)
        tv2 = findViewById(R.id.textView2)
        chip1 = findViewById(R.id.chip1)

        try {

            //拿到uri
            var uri = intent.data

            /**
             * 判断 uri 包含 file:/// 或 content://
             */
            if (uri.toString().startsWith("file:///")){

                var file = File(FileUtil.getFileAbsolutePath(this, uri))
                tv1.text = file.name
                var str = file.readText()
                tv2.text = str
                chip1.text = "字数:${str.length}"

            }else {

                var file = UriUtils(applicationContext, uri);
                tv1.text = file.fileName
                var str = file.readFileText()

                println(str)

                tv2.text = str
                chip1.text = "字数:${str.length}"

            }

        } catch (e: Exception) {
                Toast.makeText(applicationContext, "程序异常!", Toast.LENGTH_LONG).show()
            return
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

}